package com.caiheng.api.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.EstateRoom;
import com.caiheng.api.entity.estate.PropertyFeeOrder;
import com.caiheng.api.entity.estate.PropertyFeeOrderTemplate;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.platform.*;
import com.caiheng.api.entity.product.*;
import com.caiheng.api.entity.setmeal.SetMealOrder;
import com.caiheng.api.entity.wxmsg.MsgTempData;
import com.caiheng.api.entity.wxmsg.WxMsgTemplate;
import com.caiheng.api.entity.wxmsg.WxTemplate;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.entity.wxuser.UserMp;
import com.caiheng.api.pay.nongshang.NSHUtils;
import com.caiheng.api.pay.utils.RSA;
import com.caiheng.api.pay.wxpay.WXPayCommonUtil;
import com.caiheng.api.pay.wxpay.WxAppPay;
import com.caiheng.api.service.estate.EstateRoomService;
import com.caiheng.api.service.estate.PropertyFeeOrderService;
import com.caiheng.api.service.estate.PropertyFeeOrderTemplateService;
import com.caiheng.api.service.mer.MerService;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.product.*;
import com.caiheng.api.service.setmeal.SetMealOrderService;
import com.caiheng.api.service.wxuser.*;

import com.vdurmont.emoji.EmojiParser;
import com.caiheng.api.util.*;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  订单列表
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/pay")//url:模块/资源/{}/细分
public class PayController extends BaseController {

    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private SetMealOrderService setMealOrderService;
    @Resource
    private UserService userService;
    @Resource
    private UserCouponsService userCouponsService;
    @Resource
    private UserMerCouponService userMerCouponService;
    @Resource
    private UserMpService userMpService;
    @Resource
    private ProductService productService;
    @Resource
    private PropertyFeeOrderService feeOrderService;
    @Resource
    private PropertyFeeOrderTemplateService feeOrderTemplateService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private ProductOrderRelationService orderRelationService;
    @Resource
    private MerService merService;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private SmsTemplateService smsTemplateService;
    @Resource
    private WxPayTransactionService payTransactionService;
    @Resource
    private PlatformPayService platformPayService;
    @Resource
    private PropertyFeeOrderService propertyFeeOrderService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${web.wx_notify_url}")
    private String wx_notify_url;//微信支付的回调地址

    @Value("${web.keyPath}")
    private String keyPath;//微信支付的回调地址

    @Value("${web.wx_refund_notify_url}")
    private String wx_refund_notify_url;//微信支付的回调地址

    @Value("${web.appid}")
    private String appid;
    @Value("${web.secret}")
    private String secret;
    @Value("${web.mch_id}")
    private String mch_id;
    @Value("${web.api_key}")
    private String api_key;


    @Value("${web.nsh_wyf_notify_url}")
    private String nsh_wyf_notify_url;

    @Value("${web.nsh_notify_url}")
    private String nsh_notify_url;

    @Resource
    private LockTemplate lockTemplate;



    /**
     * 调起支付
     * @return
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;

//            ProductOrder order = productOrderService.findById(order_id);
//            User user = userService.findById(user_id);
//            sendWxMsg(user, order, 7);
//
//            PlatformPay platformPay = platformPayService.getDefaultAccount();

//            WxAppPay wxAppPay = new WxAppPay(wx_notify_url, secret, appid, mch_id, api_key);
//            String retRequest = wxAppPay.weiXinOrderQuery("32WT1705113071279");
            //{"nonce_str":"OzeEbikjwqebSk8t","device_info":"","trade_state":"NOTPAY","out_trade_no":"32WT1705111756068",
            // "appid":"wxf6d65dcf0668b400","total_fee":"10","trade_state_desc":"订单未支付","sign":"3655FD1C3B41AE20CEAD159C4FCDDF9D",
            // "return_msg":"OK","result_code":"SUCCESS","mch_id":"1665434855","return_code":"SUCCESS"}

//            System.out.println(retRequest);

            productOrderService.resetOrderFee();

//            Integer[] states = {0, 1, 5};
//            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
//            qw.ne("order_type",6);
//            qw.in("status", Arrays.asList(states));
//            List<ProductOrder> orderList = productOrderService.list(qw);
//            if (CollUtil.isNotEmpty(orderList)) {
//                for (ProductOrder productOrder : orderList) {
//                    WxAppPay wxAppPay = new WxAppPay(wx_notify_url, secret, appid, mch_id, api_key);
//                    String retRequest = wxAppPay.weiXinOrderQuery(productOrder.getOutTradeNo());
//                    System.out.println("查询结果： " + retRequest);
//                    JSONObject jsonObject = JSONUtil.parseObj(retRequest);
//                    if(jsonObject != null){
//                        String result_code = jsonObject.getStr("result_code");
//                        if(result_code.equals("SUCCESS")){
//                            String trade_state = jsonObject.getStr("trade_state");
//                            if(trade_state.equals("NOTPAY")){
//                                System.out.println(" 取消后 未支付");
////                                Date createTime = productOrder.getCreateTime();
////                                Date checkTime = DateUtil.getAfterSecondsByOld(createTime, 4 * 60);
////                                if (new Date().getTime() > checkTime.getTime()) {
////                                }
//                                //取消订单
//                                productOrder.setStatus(5);
//                                productOrderService.updateById(productOrder);
//                            }else if(trade_state.equals("SUCCESS")){
//                                System.out.println(" 取消后  支付成功");
//                                String transaction_id = jsonObject.getStr("transaction_id");
//
//                                String total_amount = jsonObject.getStr("total_fee");
//                                double total_amount_double = Double.valueOf(total_amount) / 100;
//
//                                productOrder.setStatus(3);
//                                productOrder.setTransactionId(transaction_id);
//                                productOrder.setPayPrice(new BigDecimal(total_amount_double));
//                                //更改订单支付状态
//                                productOrder.setIsMerCheck(2);
//                                productOrder.setVerifyTime(new Date());
//                                productOrderService.buyNormalUpdate(productOrder, null);
//                            }
//                        }else{
//                            String err_code =  jsonObject.containsKey("err_code") ? jsonObject.getStr("err_code") : "";
//                            System.out.println("查询结果  描述" + err_code);
//                        }
//                    }
//                }
//            }


//
//            String orderNo = OrderUtil.getOrderNoByTimespan();
//            String retJson = NSAppletOrders.addOrderByQr(orderNo, platformPay, new BigDecimal(0.01), "", nsh_notify_url ,"");
//            System.out.println("二维码获取：" + retJson);


        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 调起退款(发起退款操作)
     * @return
     */
    @PostMapping(value = "/requestRefund")
    public JSONObject requestRefund(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;
            String reason = jsonRequest.containsKey("reason") ? jsonRequest.getStr("reason") : "";

            boolean blIsMineOrder = false;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

//            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请联系客服退款"),true,true);
//

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            ProductOrder orders = productOrderService.findById(order_id);
            if(orders != null){
                platformPay = platformPayService.getById(orders.getPayPlatformId());

                orders.setRefundReasonWapExplain(reason);
                if(orders.getUserId().intValue() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单不属于你"),true,true);
                }

                if(orders.getIsMerCheck() == 1){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单已核销，不能发起退款"),true,true);
                }

                if(orders.getStatus() == 7){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单在退款中请耐心等待"),true,true);
                } else if(orders.getStatus() == 8){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单已退款完成"),true,true);
                }

                blIsMineOrder = true;
                String out_refund_no = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
                orders.setRefundOutTradeNo(out_refund_no);

                if(orders.getStatus() == 2){
                    if(blIsMineOrder) {
                        //String out_trade_no, BigDecimal refund_money, String out_refund_no,PlatformPay platformPay
                        String retRequest = platformPayService.refundOrder(orders.getOutTradeNo(), orders.getPayPrice(),orders.getRefundOutTradeNo(),platformPay);
                        System.out.println("retRequest: " + retRequest);
                        JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                        if(jsonObject!=null){
                            String errCode = jsonObject.getStr("errCode");
                            String errMsg = jsonObject.getStr("errMsg");
                            String refundStatus = jsonObject.getStr("refundStatus");
                            if(errCode.equals("SUCCESS") && refundStatus.equals("SUCCESS")){
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请求成功"),true,false);
                                orders.setStatus(7);//同意退货
                                productOrderService.updateById(orders);
                            }else{
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,errMsg),true,true);
                            }
                        }
                    }else{//当前订单不属于您
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
                    }
                }else{//当前订单不属于您
                    ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该状态下不能发起退款"),true,true);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 微信小程序调起支付
     * @return
     */
    @PostMapping(value = "/requestPay")
    public JSONObject requestPay(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;

        if(StrUtil.isEmpty(requestParam)){
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
        }
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;
        final LockInfo lockInfo = lockTemplate.lock(order_id + "_requestPayOffline", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{

            String subject = jsonRequest.containsKey("subject") ? jsonRequest.getStr("subject") : "";
            int isAppointment = jsonRequest.containsKey("isAppointment") ? jsonRequest.getInt("isAppointment") : 0;
            String appointmentName = jsonRequest.containsKey("appointmentName") ? jsonRequest.getStr("appointmentName") : null;
            String appointmentAddress = jsonRequest.containsKey("appointmentAddress") ? jsonRequest.getStr("appointmentAddress") : null;
            String appointmentPhone = jsonRequest.containsKey("appointmentPhone") ? jsonRequest.getStr("appointmentPhone") : null;
            String appointmentTime = jsonRequest.containsKey("appointmentTime") ? jsonRequest.getStr("appointmentTime") : null;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;
            String orderNo = "";
            boolean blIsMineOrder = false;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            ProductOrder orders = productOrderService.findById(order_id);
            if(orders != null){
                int orderUserId = orders.getUserId();
                if(orderUserId == user_id){
                    orderNo = orders.getOutTradeNo();
                    blIsMineOrder = true;
                }else{
                    blIsMineOrder = false;
                }

                Mer mer = merService.findById(orders.getMerId());
                if(mer!= null){
                    if(mer.getPayPlatformId() > 0){
                        platformPay = platformPayService.getById(mer.getPayPlatformId());
                    }
                }



                Product product = productService.getProductByOrderId(order_id);
                if(product!= null){
                    if(product.getIsSaleOut() == 1){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该商品已售罄"), true, true);
                    }
                }

                if(orders.getStatus() == 0 || orders.getStatus() == 1){//如果是 再次提交支付的话，订单号要生成新的
                    orderNo = OrderUtil.getOrderNoByTimespan();
                    if(orders.getPayType() == 1) {
                        orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
                    }
                    orders.setOutTradeNo(orderNo);
                }else if(orders.getStatus() == 2 || orders.getStatus() == 3 || orders.getStatus() == 4){
                    /**
                     * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
                     * 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货  10 - 团购成功 11 - 团购失败
                     */
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"订单已支付"),true,true);
                } else if(orders.getStatus() == 5){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"订单已取消"),true,true);
                }
                else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能发起支付"),true,true);
                }

                //可预约的 预约信息
                orders.setIsAppointment(isAppointment);
                //可预约的 预约信息
//                if(isAppointment == 1){
                    if(StrUtil.isNotEmpty(appointmentName)){
                        orders.setAppointmentName(appointmentName);
                    }
                    if(StrUtil.isNotEmpty(appointmentAddress)){
                        orders.setAppointmentAddress(appointmentAddress);
                    }
                    if(StrUtil.isNotEmpty(appointmentPhone)){
                        orders.setAppointmentPhone(appointmentPhone);
                    }
                    if(StrUtil.isNotEmpty(appointmentTime)){
                        orders.setAppointmentTime(DateUtil.ConvertDateByformat(appointmentTime,"yyyy-MM-dd HH:mm:ss"));
                    }
                    if(StrUtil.isNotEmpty(remark)){
                        orders.setAppointmentRemark(remark);
                    }
//                }
                if(StrUtil.isNotEmpty(remark)){
                    orders.setRemark(remark);
                }
            }

            if(blIsMineOrder){
                if(orders.getPayPrice().doubleValue() > 0) {
                    if (orders.getPayType() == 0) {
                        WxAppPay wxAppPay = new WxAppPay(wx_notify_url, secret, appid, mch_id, api_key);
                        String retRequest = wxAppPay.weiXinPrePay(orders.getOutTradeNo(), orders.getTotalPrice(), subject,
                                request.getRemoteAddr(), user.getOpenId(), "NORMAL");
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "请求成功", retRequest), true, false);
                        orders.setStatus(1);//支付中
                        productOrderService.updateById(orders);
                    } else {
                        String retRequest = platformPayService.appletOrderMain(orderNo, orders.getPayPrice(), subject, user.getOpenId(), "NORMAL", nsh_notify_url, platformPay);
                        System.out.println("retRequest: " + retRequest);
                        JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                        if (jsonObject != null) {
                            String errCode = jsonObject.getStr("errCode");
                            String errMsg = jsonObject.getStr("errMsg");
                            if (errCode.equals("SUCCESS")) {
                                JSONObject retData = jsonObject.getJSONObject("miniPayRequest");
                                retData.set("result_code", "SUCCESS");
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "请求成功", retData.toString()), true, false);
                                orders.setStatus(1);//支付中
                                productOrderService.updateById(orders);
                            } else {
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, errMsg), true, true);
                            }
                        }
                    }

                }else{
                    JSONObject retData = new JSONObject();
                    retData.set("result_code", "NOTNEEDPAY");
                    ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "请求成功"), true, false);
                    orders.setStatus(2);//无需支付的情况，抵扣完了
                    productOrderService.buyNormalUpdate(orders,user);

                }

            }else{//当前订单不属于您
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return ret;
    }

    /**
     *  线下支付调起支付
     * @return
     */
    @PostMapping(value = "/requestPayOffline")
    public JSONObject requestPayOffline(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;

        if(StrUtil.isEmpty(requestParam)){
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
        }
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;
        String subject = jsonRequest.containsKey("subject") ? jsonRequest.getStr("subject") : "";
        String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";

        final LockInfo lockInfo = lockTemplate.lock(order_id + "_requestPayOffline", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            boolean blIsMineOrder = false;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            ProductOrder orders = productOrderService.findById(order_id);
            if(orders != null){
                orders.setRemark(remark);
                int orderUserId = orders.getUserId();
                if(orderUserId == user_id){
                    blIsMineOrder = true;
                }

                Mer mer = merService.findById(orders.getMerId());
                if(mer!= null){
                    if(mer.getPayPlatformId() > 0){
                        platformPay = platformPayService.getById(mer.getPayPlatformId());
                    }
                }

                if(orders.getPayType() == 1){
                    if(orders.getPayPlatformId()!= null && orders.getPayPlatformId() > 0){
                        platformPay = platformPayService.getById(orders.getPayPlatformId());
                    }
                }

                String orderNo = "";
                if(orders.getStatus() == 1){//如果是 再次提交支付的话，订单号要生成新的
                    orderNo = OrderUtil.getOrderNoByTimespan();
                    if(orders.getPayType() == 1) {
                        orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
                    }
                    orders.setOutTradeNo(orderNo);
                }else if(orders.getStatus() >= 2){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能发起支付"),true,true);
                }

                if(orders.getIsDel() == 1){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能发起支付"),true,true);
                }

                if(orders.getIsMerCheck() == 2){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单已核销，不能支付"),true,true);
                }

                if(blIsMineOrder){
                    if(orders.getPayType() == 0) {
                        WxAppPay wxAppPay = new WxAppPay(wx_notify_url, secret, appid, mch_id, api_key);
                        String retRequest = wxAppPay.weiXinPrePay(orders.getOutTradeNo(), orders.getTotalPrice(), subject,
                                request.getRemoteAddr(), user.getOpenId(), "OFFLINE");
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "请求成功", retRequest), true, false);
                        orders.setStatus(1);//支付中
                        productOrderService.updateById(orders);
                    } else {
                        String retRequest = platformPayService.appletOrderMain(orders.getOutTradeNo(), orders.getPayPrice(), subject, user.getOpenId(), "OFFLINE", nsh_notify_url, platformPay);
                        System.out.println("retRequest: " + retRequest);
                        JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                        if (jsonObject != null) {
                            String errCode = jsonObject.getStr("errCode");
                            String errMsg = jsonObject.getStr("errMsg");
                            if (errCode.equals("SUCCESS")) {
                                JSONObject retData = jsonObject.getJSONObject("miniPayRequest");
                                retData.set("result_code", "SUCCESS");
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "请求成功", retData.toString()), true, false);
                                orders.setStatus(1);//支付中
                                productOrderService.updateById(orders);
                            } else {
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, errMsg), true, true);
                            }
                        }
                    }
                }else{//当前订单不属于您
                    ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return ret;
    }

    /**
     *  多个订单一次支付 调起支付
     * @return
     */
    @PostMapping(value = "/payByPayNo")
    public JSONObject requestPayByPayNo(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String payNo = jsonRequest.containsKey("pay_no") ? jsonRequest.getStr("pay_no") : null;
            String subject = jsonRequest.containsKey("subject") ? jsonRequest.getStr("subject") : "";
            if(StrUtil.isEmpty(payNo)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"订单异常，请重试"),true,true);
            }

            boolean blIsMineOrder = true;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
            qw.eq("pay_no",payNo);
            qw.ne("user_id",user_id);
            qw.last("limit 1");
            ProductOrder orders = productOrderService.getOne(qw);
            if(orders != null){
                //如果存在不是自己的 当前订单不处理
                blIsMineOrder = false;
            }

            BigDecimal allPrice = new BigDecimal(0);
            QueryWrapper<ProductOrderRelation> qwRelation = new QueryWrapper<>();
            qwRelation.eq("pay_no",payNo);
            qwRelation.last("limit 1");
            ProductOrderRelation orderRelation = orderRelationService.getOne(qwRelation);
            if(orderRelation!=null){
                allPrice = orderRelation.getAllPrice();
            }

            List<ProductOrder> orderList = productOrderService.selectListByColumn("pay_no",payNo);
            if(CollUtil.isNotEmpty(orderList)){
                for (ProductOrder order : orderList){
//                    orderNo = OrderUtil.getOrderNoByTimespan();
//                    order.setOutTradeNo(orderNo);
                    order.setStatus(1);//支付中
                    productOrderService.updateById(order);
                }
            }

            if(blIsMineOrder){

                String retRequest = platformPayService.appletOrderMain(payNo, orders.getPayPrice(),subject,user.getOpenId(),"BATCHPAY",nsh_notify_url,platformPay);
                System.out.println("retRequest: " + retRequest);
                JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                if(jsonObject!=null){
                    String errCode = jsonObject.getStr("errCode");
                    String errMsg = jsonObject.getStr("errMsg");
                    if(errCode.equals("SUCCESS")){
                        JSONObject retData = jsonObject.getJSONObject("miniPayRequest");
                        retData.set("result_code","SUCCESS");
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请求成功",retData.toString()),true,false);
                    }else{
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,errMsg),true,true);
                    }
                }

            }else{//当前订单不属于您
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 调起支付
     * @return
     */
    @PostMapping(value = "/requestPayProperty")
    public JSONObject requestPayProperty(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;

        if(StrUtil.isEmpty(requestParam)){
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
        }
        logBefore(logger, "pay/requestPayProperty 接收的参数： "+requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;
        String subject = jsonRequest.containsKey("subject") ? jsonRequest.getStr("subject") : "";

        final LockInfo lockInfo = lockTemplate.lock(order_id + "_requestPayProperty", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }
        try{
            boolean blIsMineOrder = false;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            String orderNo = "";
            PropertyFeeOrder feeOrder = feeOrderService.findById(order_id);
            if(feeOrder != null){

                EstateRoom estateRoom = estateRoomService.findById(feeOrder.getRoomId());
                if(estateRoom!=null){
                    subject += " " + estateRoom.getRoomNo();
                }

                //如果是 农商行的支付商户的话  读取农商行的支付商户信息
                if(feeOrder.getPayPlatform() == 1){
                    platformPay = platformPayService.findById(feeOrder.getPayPlatformId());
                    if(platformPay == null || feeOrder.getPayPlatformId() == null){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"支付失败，请联系客服"),true,true);
                    }

                    subject = platformPay.getPlatformName() + " " + subject;
                }

                if(feeOrder.getState() == 4){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已支付"),true,true);
                } else if(feeOrder.getState() == 5){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"订单已取消，请重新选择"),true,true);
                } else if(feeOrder.getState() > 5){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前无需支付"),true,true);
                }
                int orderUserId = feeOrder.getUserId();
                if(orderUserId == user_id){
                    orderNo = feeOrder.getOutTradeNo();
                    if(feeOrder.getState() == 3){//如果是 再次提交支付的话，订单号要生成新的
                        if(platformPay!=null){
                            orderNo = platformPay.getSysCode() + feeOrder.getEstateId() + DateUtil.getSdfffTimes();
                        }else{
                            orderNo = feeOrder.getEstateId() + DateUtil.getSdfffTimes();
                        }
                        feeOrder.setOutTradeNo(orderNo);
                        feeOrderService.updateById(feeOrder);
                    }else if(feeOrder.getState() > 3){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能发起支付"),true,true);
                    }
                    blIsMineOrder = true;
                }else{
                    blIsMineOrder = false;
                }
            }


            if(blIsMineOrder){
                if(feeOrder.getPayMoney().doubleValue() > 0){
                    if(feeOrder.getPayPlatform() == 0) {
                        //订单状态   0 - 交费申请 1 - 已生成交费清单 2 - 待支付  3- 支付中  4 - 已支付 5 - 订单取消
                        feeOrder.setState(3);//支付中
                        feeOrderService.updateById(feeOrder);
                        WxAppPay wxAppPay = new WxAppPay(wx_notify_url, secret, appid, mch_id, api_key);
                        String retRequest = wxAppPay.weiXinPrePay(orderNo,feeOrder.getPayMoney(),subject,request.getRemoteAddr(),user.getOpenId(),"WYF");
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请求成功",retRequest),true,false);
                    }else{
                        String retRequest = "";
                        if(platformPay.getMerType() != null && platformPay.getMerType() == 1){
                            retRequest = platformPayService.appletOrderUnCart(orderNo, feeOrder.getPayMoney(),subject,user.getOpenId(),"WYF",
                                    nsh_wyf_notify_url,platformPay);
                        }else{
                            retRequest = platformPayService.appletOrder(orderNo, feeOrder.getPayMoney(),subject,user.getOpenId(),"WYF",
                                    nsh_wyf_notify_url,platformPay);
                        }

                        System.out.println("retRequest: " + retRequest);
                        JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                        if(jsonObject!=null){
                            String errCode = jsonObject.getStr("errCode");
                            String errMsg = jsonObject.getStr("errMsg");
                            if(errCode.equals("SUCCESS")){
                                JSONObject retData = jsonObject.getJSONObject("miniPayRequest");
                                retData.set("result_code","SUCCESS");
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请求成功",retData.toString()),true,false);
                                feeOrder.setState(3);//支付中
                                feeOrderService.updateById(feeOrder);
                            }else{
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,errMsg),true,true);
                            }
                        }
                    }
                }
            }else{//当前订单不属于您
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return ret;
    }

    /**
     *   农商行 支付成功回调处理
     * @param params
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/nsh_notify")
    public String nshPayNotify(@RequestParam Map<String, String> params,HttpServletRequest request) throws IOException {
        System.out.println("农商行 默认支付 支付回调： " + params);
        int ret = 0;
        JSONObject jsonObject = new JSONObject(params);
        if(jsonObject!=null){
            //TRADE_SUCCESS
            String status = jsonObject.getStr("status");
            String attach = jsonObject.getStr("attachedData");
            String orderNo = jsonObject.getStr("merOrderId");

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            if(attach.equals("NORMAL") || attach.equals("OFFLINE")) {//普通商品订单
                QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
                qw.eq("out_trade_no",orderNo).or().eq("order_no", orderNo);
                ProductOrder order = productOrderService.getOne(qw);
                if(order != null){
                    Mer mer = merService.findById(order.getMerId());
                    if(mer!= null){
                        if(mer.getPayPlatformId() > 0){
                            platformPay = platformPayService.getById(mer.getPayPlatformId());
                        }
                    }
                }
            }
            boolean blIsValidate = false;
            try {
                blIsValidate = NSHUtils.validateSignNSh(params, platformPay.getApiKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(blIsValidate){
                //支付成功的推送
                if(status.equals("TRADE_SUCCESS")){
                    String result_code = status;
                    System.out.println("附加信息: " + attach);
                    try {
                        if(attach.equals("NORMAL")){//普通商品订单
                            ret = pay_success_product(params,result_code,2);//逻辑处理
                        }else if(attach.equals("WYF")){//物业费订单
                            ret = pay_success_wyf(params,result_code,2);
                        } else if(attach.equals("OFFLINE")){
                            ret = pay_success_offline(params,result_code,2);
                        }
                        if(ret > 0){
                            return "success";
                        }else{
                            return "fail";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //退款 操作
                else if(status.equals("TRADE_REFUND")){
                    //商品退款回调
                    ret = refund_success_product(params,2);
                    if(ret > 0){
                        return "success";
                    }else{
                        return "fail";
                    }
                }
            }else{
                System.out.println("验签失败： 订单号：" + orderNo);
                return "fail";
            }
        }
        // 处理业务完毕
        // ------------------------------
        return "fail";
    }

    /**
     *   农商行 支付成功回调处理 (二维码模式)
     * @param params
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/nsh_notify_qr")
    public String nshPayQrNotify(@RequestParam Map<String, String> params,HttpServletRequest request) throws IOException {
        System.out.println("农商行 默认支付 二维码模式 支付回调： " + params);
        int ret = 0;
        JSONObject jsonObject = new JSONObject(params);
        if(jsonObject!=null){
            //TRADE_SUCCESS
            String status = jsonObject.getStr("billStatus");
            String attach = jsonObject.getStr("attachedData");
            String orderNo = jsonObject.getStr("billNo");//订单号

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            boolean blIsValidate = false;
            try {
                blIsValidate = NSHUtils.validateSignNSh(params,platformPay.getApiKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(blIsValidate){
                //支付成功的推送  已支付
                if(status.equals("PAID")){
                    String result_code = status;
                    System.out.println("附加信息: " + attach);
                    try {
                        if(attach.equals("NORMAL")){//普通商品订单
                            ret = pay_success_product(params,result_code,2);//逻辑处理
                        } else if(attach.equals("WYF")){//物业费订单
                            ret = pay_success_wyf(params,result_code,2);
                        }else if(attach.equals("OFFLINE")){
                            ret = pay_success_offline(params,result_code,2);
                        }
                        if(ret > 0){
                            return "success";
                        }else{
                            return "fail";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //退款 操作
                else if(status.equals("REFUND")){
                    //商品退款回调
                    ret = refund_success_product(params,2);
                    if(ret > 0){
                        return "success";
                    }else{
                        return "fail";
                    }
                }
            }else{
                System.out.println("验签失败： 订单号：" + orderNo);
                return "fail";
            }
        }
        // 处理业务完毕
        // ------------------------------
        return "fail";
    }

    /**
     *   农商行 支付成功回调处理
     * @param params
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/nsh_notify_wyf")
    public String nshPayWyfNotify(@RequestParam Map<String, String> params,HttpServletRequest request) throws IOException {
        System.out.println("农商行  物业费支付  支付回调： " + params);
        int ret = 0;
        JSONObject jsonObject = new JSONObject(params);
        if(jsonObject!=null){
            //TRADE_SUCCESS
            String status = jsonObject.getStr("status");
            String attach = jsonObject.getStr("attachedData");
            String orderNo = jsonObject.getStr("merOrderId");

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",orderNo).or().eq("order_no",orderNo);
            qw.last("limit 1");
            PropertyFeeOrder feeOrder = propertyFeeOrderService.getOne(qw);
            if(feeOrder != null){
                platformPay = platformPayService.getById(feeOrder.getPayPlatformId());
            }

            boolean blIsValidate = false;
            try {
                blIsValidate = NSHUtils.validateSignNSh(params,platformPay.getApiKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(blIsValidate){
                System.out.println("验签成功： 订单号：" + orderNo);
                //支付成功的推送
                if(status.equals("TRADE_SUCCESS")){
                    String result_code = status;
                    System.out.println("附加信息: " + attach);
                    try {
                        if(attach.equals("WYF")){//物业费订单
                            ret = pay_success_wyf(params,result_code,2);
                        }
                        if(ret > 0){
                            return "success";
                        }else{
                            return "fail";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //退款 操作
                else if(status.equals("TRADE_REFUND")){
                    //退款回调
                    ret = refund_success_wyf(params,2);
                }
            }else{
                System.out.println("验签失败： 订单号：" + orderNo);
                return "fail";
            }
        }
        // 处理业务完毕
        // ------------------------------
        return "fail";
    }

    /**
     *   农商行 充电套餐 支付成功回调处理
     * @param params
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/nsh_notify_setmeal")
    public String nshPaySetMealNotify(@RequestParam Map<String, String> params,HttpServletRequest request) throws IOException {
        System.out.println("农商行  套餐活动支付 支付回调： " + params);
        int ret = 0;
        JSONObject jsonObject = new JSONObject(params);
        if(jsonObject!=null){
            //TRADE_SUCCESS
            String status = jsonObject.getStr("status");
            String attach = jsonObject.getStr("attachedData");
            String orderNo = jsonObject.getStr("merOrderId");

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            boolean blIsValidate = false;
            try {
                blIsValidate = NSHUtils.validateSignNSh(params,platformPay.getApiKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(blIsValidate){
                //支付成功的推送
                if(status.equals("TRADE_SUCCESS")){
                    String result_code = status;
                    System.out.println("附加信息: " + attach);
                    try {
                        if(attach.equals("MEAL")){  // 套餐活动 支付
                            ret = pay_success_meal(params,result_code,2);
                        }
                        if(ret > 0){
                            return "success";
                        }else{
                            return "fail";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //退款 操作
                else if(status.equals("TRADE_REFUND")){
                    //商品退款回调
                }
            }else{
                System.out.println("验签失败： 订单号：" + orderNo);
                return "fail";
            }
        }
        // 处理业务完毕
        // ------------------------------
        return "fail";
    }

    /**
     * 微信支付成功回调处理
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/wxpay_notify")
    public String wxpayProductNotify(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        int ret = 0;
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultXml = new String(outSteam.toByteArray(), "utf-8");
        System.out.println("微信支付回调:" + resultXml);
        Map<String, String> params = null;
        try {
            params = WXPayCommonUtil.doXMLParse(resultXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        outSteam.flush();
        outSteam.close();
        inStream.close();
        if (!WXPayCommonUtil.isTenpaySign(params,api_key)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            // ------------------------------
            String result_code = params.get("result_code");
            String attach = params.get("attach");
            System.out.println("附加信息: " + attach);
            try {
                if(attach.equals("NORMAL")){//普通商品订单
                    ret = pay_success_product(params,result_code,1);//逻辑处理
                } else if(attach.equals("BATCHPAY")){//  多个商家的订单一起提交支付的回调
                    ret = pay_success_product_batch(params,result_code,1);//逻辑处理
                } else if(attach.equals("WYF")){//物业费订单
                    ret = pay_success_wyf(params,result_code,1);
                } else if(attach.equals("OFFLINE")){
                    ret = pay_success_offline(params,result_code,1);
                }else if(attach.equals("MEAL")){  // 套餐活动 支付
                    ret = pay_success_meal(params,result_code,1);
                }

                if(ret > 0){
                    return "success";
                }else{
                    return "fail";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 处理业务完毕
            // ------------------------------
            return "fail";
        }
    }

    /**
     * 微信支付退款回调处理
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/wxpay_refund_notify")
    public String wxPayRefundNotify(HttpServletRequest request) throws IOException {
        System.out.println("微信支付退款回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        int ret = 0;
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultXml = new String(outSteam.toByteArray(), "utf-8");
        System.out.println("微信退款处理成功回调:" + resultXml);
        Map<String, String> params = null;
        try {
            params = WXPayCommonUtil.doXMLParse(resultXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        outSteam.flush();
        outSteam.close();
        inStream.close();
        System.out.println("===============退款处理成功==============");
        // ------------------------------
        // 处理业务开始
        // ------------------------------
        // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
        // ------------------------------
        String return_code = params.get("return_code");
        String attach = params.get("attach");
        System.out.println("附加信息: " + attach);
        String req_info = params.get("req_info");
        try {
            if(return_code.equals("SUCCESS")){
                String descrypt = RSA.descrypt(req_info,api_key);
                Map<String,String> reqInfoMap = WXPayCommonUtil.doXMLParse(descrypt);
                ret = refund_success_product(reqInfoMap,1);
                if(ret > 0){
                    return "success";
                }else{
                    return "fail";
                }
            }
            return "fail";
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 处理业务完毕
        // ------------------------------
        return "fail";
    }

    /**
     * 商品订单的   成功之后的 业务处理
     * @param params
     * @param trade_status
     * @param payType
     * @return
     */
    @SuppressWarnings("unchecked")
    private int pay_success_offline(Map<String, String> params,String trade_status,int payType){
        String out_trade_no = "";// 本平台  商户订单号
        if(params.containsKey("merOrderId")){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        } else if(params.containsKey("out_trade_no")){
            out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        }
        int ret = 0;
        try{
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",out_trade_no).or().eq("order_no",out_trade_no);
            ProductOrder order = productOrderService.getOne(qw);
            if(order != null){
                User user = userService.findById(order.getUserId());
                if(order.getStatus() == 0 || order.getStatus() == 1 || order.getStatus() == 5) {//支付中的 状态 才往下执行
                    String total_amount = "";//  订单金额
                    String trade_no = "";//  订单号
                    double total_amount_double = 0;
                    String payTime = "";
                    if (trade_status.equals("SUCCESS") || trade_status.equals("TRADE_SUCCESS")) {
                        if (payType == 1) {//微信支付参数
                            total_amount = params.get("total_fee");
                            trade_no = params.get("transaction_id");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("time_end");
                            order.setPayTime(DateUtil.getDateByString(payTime));
                        } else if (payType == 2) {// 农商行 支付参数
                            total_amount = params.get("totalAmount");
                            trade_no = params.get("targetOrderId");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("payTime");
                            order.setPayTime(DateUtil.fomatTime(payTime));
                        }

                        //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                        // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                        order.setStatus(3);
                        order.setTransactionId(trade_no);
                        order.setPayPrice(new BigDecimal(total_amount_double));
                        //更改订单支付状态
                        order.setIsMerCheck(2);
                        order.setVerifyTime(new Date());
                        ret = productOrderService.buyNormalOffline(order);
                        if(ret > 0){
                            //支付成功通知
                            sendWxMsg(user,order,7);
                        }

                        // 添加 微信支付的 动账记录
                        WxPayTransaction transaction = new WxPayTransaction();
                        transaction.setEstateId(order.getEstateId());
                        transaction.setPayType(payType);// 0 -微信支付
                        transaction.setTransactionId(trade_no);
                        transaction.setUserId(user.getId());
                        transaction.setFeeType("mer_offline");
                        transaction.setTotalMoney(new BigDecimal(total_amount_double));
                        transaction.setOutTradeNo(out_trade_no);
                        if(StrUtil.isNotEmpty(user.getNickName())){
                            transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                        }
                        transaction.setCreateTime(new Date());
                        transaction.setInOrOut(1);//动账  0 - 出账 1 - 进账
                        transaction.setRemark("商家线下支付费用");
                        transaction.setPayPlatformId(order.getPayPlatformId());

                        payTransactionService.save(transaction);

                        System.out.println("=====支付成功====");
                        logger.info("线下支付订单号：" + out_trade_no + "支付成功");
                    }
                }
            }else{
                System.out.println("线下支付订单号：" + out_trade_no + "不存在");
                logger.error("线下支付订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(""+ex.getMessage());
        }
        return ret;
    }

    /**
     * 套餐活动   成功之后的 业务处理
     * @param params
     * @param trade_status
     * @param payType
     * @return
     */
    @SuppressWarnings("unchecked")
    private int pay_success_meal(Map<String, String> params,String trade_status,int payType){
        String out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        if(payType == 2){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        }
        int ret = 0;
        try{
            QueryWrapper<SetMealOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",out_trade_no).or().eq("order_no",out_trade_no);
            qw.last("limit 1");
            SetMealOrder order = setMealOrderService.getOne(qw);
            if(order != null){
                User user = userService.findById(order.getUserId());
                if(order.getStatus() == 0 || order.getStatus() == 1) {//支付中的 状态 才往下执行
                    String total_amount = "";//  订单金额
                    String trade_no = "";//  订单号
                    double total_amount_double = 0;
                    String payTime = "";
                    if (trade_status.equals("SUCCESS") || trade_status.equals("TRADE_SUCCESS")) {
                        if (payType == 0) {//支付宝支付参数
                            total_amount = params.get("total_amount");
                            trade_no = params.get("trade_no");//支付宝支付订单号
                            total_amount_double = Double.valueOf(total_amount);
                        } else if (payType == 1) {//微信支付参数
                            total_amount = params.get("total_fee");
                            trade_no = params.get("transaction_id");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("time_end");
                        } else if (payType == 2) {// 农商行 支付参数
                            total_amount = params.get("totalAmount");
                            trade_no = params.get("targetOrderId");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("payTime");
                        }

                        //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                        // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                        order.setStatus(2);
                        order.setTransactionId(trade_no);
                        order.setPayPrice(new BigDecimal(total_amount_double));
                        order.setPayTime(new Date());
                        ret = setMealOrderService.buyMeal(order);
                        if(ret > 0){
                            System.out.println("=====支付成功====");
                            logger.info("套餐活动 订单号：" + out_trade_no + "支付成功");
                        }else{

                        }

                        // 添加 微信支付的 动账记录
                        WxPayTransaction transaction = new WxPayTransaction();
                        transaction.setEstateId(order.getEstateId());
                        transaction.setEstateName(order.getEstateName());
                        transaction.setPayType(payType);// 0 -微信支付
                        transaction.setTransactionId(trade_no);
                        transaction.setUserId(user.getId());
                        transaction.setFeeType("meal");
                        transaction.setTotalMoney(new BigDecimal(total_amount_double));
                        transaction.setOutTradeNo(out_trade_no);
                        if(StrUtil.isNotEmpty(user.getNickName())){
                            transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                        }
                        transaction.setCreateTime(new Date());
                        transaction.setInOrOut(1);//动账  0 - 出账 1 - 进账
                        transaction.setRemark("套餐活动支付费用");
                        transaction.setPayPlatformId(order.getPayPlatformId());
                        payTransactionService.save(transaction);

                    }
                }
            }else{
                System.out.println("套餐活动订单号：" + out_trade_no + "不存在");
                logger.error("套餐活动订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(""+ex.getMessage());
        }
        return ret;
    }

    /**
     * 商品订单的   成功之后的 业务处理
     * @param params
     * @param trade_status
     * @param payType
     * @return
     */
    @SuppressWarnings("unchecked")
    private int pay_success_product(Map<String, String> params,String trade_status,int payType){
        String out_trade_no = "";// 本平台  商户订单号
        if(params.containsKey("merOrderId")){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        } else if(params.containsKey("out_trade_no")){
            out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        }
        int ret = 0;
        try{
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",out_trade_no).or().eq("order_no",out_trade_no);
            ProductOrder order = productOrderService.getOne(qw);
            if(order != null){
                User user = userService.findById(order.getUserId());
                if(order.getStatus() == 0 || order.getStatus() == 1 || order.getStatus() == 5) {//支付中的 状态 才往下执行
                    String total_amount = "";//  订单金额
                    String trade_no = "";//  订单号
                    double total_amount_double = 0;
                    String payTime = "";
                    if (trade_status.equals("SUCCESS") || trade_status.equals("TRADE_SUCCESS")) {
                        if (payType == 0) {//支付宝支付参数
                            total_amount = params.get("total_amount");
                            trade_no = params.get("trade_no");//支付宝支付订单号
                            total_amount_double = Double.valueOf(total_amount);
                        } else if (payType == 1) {//微信支付参数
                            total_amount = params.get("total_fee");
                            trade_no = params.get("transaction_id");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("time_end");
                        } else if (payType == 2) {// 农商行 支付参数
                            total_amount = params.get("totalAmount");
                            trade_no = params.get("targetOrderId");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("payTime");
                        }

                        //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                        // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                        order.setStatus(2);
                        order.setTransactionId(trade_no);
                        order.setPayPrice(new BigDecimal(total_amount_double));
                        order.setPayTime(new Date());
                        ret = productOrderService.buyNormalUpdate(order,user);
                        if(ret > 0){
                            //支付成功通知
                            sendWxMsg(user,order,7);
                            //String merName, String phoneNum, String productName
                            if(order.getOrderType() == 0 || order.getOrderType() == 4){
                                try{
                                    Product product = productService.getProductByOrderId(order.getId());
                                    if(product!=null){
                                        Mer mer = merService.findById(order.getMerId());
                                        if(mer != null){
                                            if(order.getIsAppointment() == 0){//非上门预约类
                                                smsTemplateService.sendSmsByProductOrder(mer.getShopName(),mer.getTelphone(), product.getStoreName());
                                            }else{//上门服务类。
                                                smsTemplateService.sendSmsByProductOrderVisit(mer.getShopName(),mer.getTelphone(),product.getStoreName());
                                            }
                                        }
                                    }
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }
                        }

                        // 添加 微信支付的 动账记录
                        WxPayTransaction transaction = new WxPayTransaction();
                        transaction.setEstateId(order.getEstateId());
//                        transaction.setEstateName(order.getEstateName());
                        transaction.setPayType(payType);// 0 -微信支付
                        transaction.setTransactionId(trade_no);
                        transaction.setUserId(user.getId());
                        transaction.setFeeType("product");
                        transaction.setTotalMoney(new BigDecimal(total_amount_double));
                        transaction.setOutTradeNo(out_trade_no);
                        if(StrUtil.isNotEmpty(user.getNickName())){
                            transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                        }
                        transaction.setCreateTime(new Date());
                        transaction.setInOrOut(1);//动账  0 - 出账 1 - 进账
                        transaction.setRemark("购买商品/服务");
                        transaction.setPayPlatformId(order.getPayPlatformId());
                        payTransactionService.save(transaction);
                        System.out.println("=====支付成功====");
                        logger.info("普通商品订单号：" + out_trade_no + "支付成功");
                    }
                }
            }else{
                System.out.println("普通商品订单号：" + out_trade_no + "不存在");
                logger.error("普通商品订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(""+ex.getMessage());
        }
        return ret;
    }

    /**
     *  商品订单的   成功之后的 业务处理
     * @param params
     * @param trade_status
     * @param payType
     * @return
     */
    @SuppressWarnings("unchecked")
    private int pay_success_product_batch(Map<String, String> params,String trade_status,int payType){
        String out_trade_no = "";// 本平台  商户订单号
        if(params.containsKey("merOrderId")){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        } else if(params.containsKey("out_trade_no")){
            out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        }
        int ret = 0;
        try{
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
            qw.eq("pay_no",out_trade_no);
            List<ProductOrder> orderList = productOrderService.list(qw);
            if(CollUtil.isNotEmpty(orderList)){
                for (ProductOrder order : orderList){
                    if(order != null){
                        User user = userService.findById(order.getUserId());
                        if(order.getStatus() == 0 || order.getStatus() == 1) {//支付中的 状态 才往下执行
                            String total_amount = "";//  订单金额
                            String trade_no = "";//  订单号
                            double total_amount_double = 0;
                            String payTime = "";
                            if (trade_status.equals("SUCCESS") || trade_status.equals("TRADE_SUCCESS")) {
                                if (payType == 0) {//支付宝支付参数
                                    total_amount = params.get("total_amount");
                                    trade_no = params.get("trade_no");//支付宝支付订单号
                                    total_amount_double = Double.valueOf(total_amount);
                                } else if (payType == 1) {//微信支付参数
                                    total_amount = params.get("total_fee");
                                    trade_no = params.get("transaction_id");//微信支付订单号
                                    total_amount_double = Double.valueOf(total_amount) / 100;
                                    payTime = params.get("time_end");
                                } else if (payType == 2) {// 农商行 支付参数
                                    total_amount = params.get("totalAmount");
                                    trade_no = params.get("targetOrderId");//微信支付订单号
                                    total_amount_double = Double.valueOf(total_amount) / 100;
                                    payTime = params.get("payTime");
                                }

                                //订单状态   0 - 待支付  1 - 支付中  2 - 已支付，待上线
                                // 3 - 取消订单 4 - 已上线，检车中  5 - 检车成功
                                // 6 - 检车失败  7 - 退款中  8 - 已退款
                                order.setStatus(2);
                                order.setTransactionId(trade_no);
                                order.setPayPrice(new BigDecimal(total_amount_double));
                                order.setPayTime(new Date());
                                ret = productOrderService.buyNormalUpdate(order,user);
                                if(ret > 0){
                                    //支付成功通知
                                    sendWxMsg(user,order,7);
                                }


                                // 添加 微信支付的 动账记录
                                WxPayTransaction transaction = new WxPayTransaction();
                                transaction.setEstateId(order.getEstateId());
//                                transaction.setEstateName(order.getEstateName());
                                transaction.setPayType(payType);// 0 -微信支付
                                transaction.setTransactionId(trade_no);
                                transaction.setUserId(user.getId());
                                transaction.setFeeType("product");
                                transaction.setTotalMoney(new BigDecimal(total_amount_double));
                                transaction.setOutTradeNo(out_trade_no);
                                if(StrUtil.isNotEmpty(user.getNickName())){
                                    transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                                }
                                transaction.setCreateTime(new Date());
                                transaction.setInOrOut(1);//动账  0 - 出账 1 - 进账
                                transaction.setRemark("购买商品/服务，合并支付");
                                transaction.setPayPlatformId(order.getPayPlatformId());
                                payTransactionService.save(transaction);

                                System.out.println("=====支付成功====");
                                logger.info("普通商品订单号：" + out_trade_no + "支付成功");
                            }
                        }
                    }else{
                        System.out.println("普通商品订单号：" + out_trade_no + "不存在");
                        logger.error("普通商品订单号：" + out_trade_no + "不存在");
                    }
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(""+ex.getMessage());
        }
        return ret;
    }

    /**
     * 物业费缴费 处理
     * @param params
     * @param trade_status
     */
    @SuppressWarnings("unchecked")
    private int pay_success_wyf(Map<String, String> params,String trade_status,int payType){
        String out_trade_no = "";// 本平台  商户订单号
        if(params.containsKey("merOrderId")){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        } else if(params.containsKey("out_trade_no")){
            out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        }
        int ret = 0;
        try{
            QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
            qw.eq("order_no",out_trade_no).or().eq("out_trade_no",out_trade_no);
            qw.last("limit  1");
            PropertyFeeOrder orders = feeOrderService.getOne(qw);
            if(orders != null){
                if(orders.getState() == 2 || orders.getState() == 3 || orders.getState() == 5) {//支付中的 状态 才往下执行
                    String total_amount = "";//  订单金额
                    String trade_no = "";//  订单号
                    double total_amount_double = 0;
                    String payTime = "";
                    if (trade_status.equals("SUCCESS") || trade_status.equals("TRADE_SUCCESS")) {
                        if (payType == 0) {//支付宝支付参数
                            total_amount = params.get("total_amount");
                            trade_no = params.get("trade_no");//支付宝支付订单号
                            total_amount_double = Double.valueOf(total_amount);
                            payTime = params.get("time_end");
                        } else if (payType == 1) {//微信支付参数
                            total_amount = params.get("total_fee");
                            trade_no = params.get("transaction_id");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime = params.get("time_end");
                        } else if (payType == 2) {// 农商行 支付参数
                            total_amount = params.get("totalAmount");
                            trade_no = params.get("targetOrderId");//微信支付订单号
                            total_amount_double = Double.valueOf(total_amount) / 100;
                            payTime =  params.get("payTime");
                        }

                        //订单状态   0 - 交费申请 1 - 已生成交费清单 2 - 待支付
                        // 3- 支付中  4 - 已支付 5 - 订单取消
                        orders.setState(4);
                        orders.setTransactionId(trade_no);
                        orders.setPayMoney(new BigDecimal(total_amount_double));
                        orders.setPayTime(DateUtil.fomatTime(payTime));


                        QueryWrapper<PropertyFeeOrderTemplate> qwOrder = new QueryWrapper<>();
                        qwOrder.eq("fee_order_id",orders.getId());
                        qwOrder.eq("state", 0);
                        List<PropertyFeeOrderTemplate> orderTemplates = feeOrderTemplateService.list(qwOrder);
                        if(CollUtil.isNotEmpty(orderTemplates)){
                            for (PropertyFeeOrderTemplate template : orderTemplates){
                                template.setState(1);
                                feeOrderTemplateService.updateById(template);
                            }
                        }

                        ret = feeOrderService.payOver(orders,orderTemplates);

                        User user = userService.findById(orders.getUserId());

                        QueryWrapper<WxPayTransaction> qwTrans = new QueryWrapper<>();
                        qwTrans.eq("fee_type","wyf");
                        qwTrans.eq("user_id",orders.getUserId());
                        qwTrans.eq("transaction_id",trade_no);
                        qwTrans.last("limit 1");
                        WxPayTransaction transaction = payTransactionService.getOne(qwTrans);
                        if(transaction == null){
                            transaction = new WxPayTransaction();
                            transaction.setEstateId(orders.getEstateId());
                            transaction.setEstateName(orders.getEstateName());
                            transaction.setPayType(payType);// 0 -微信支付
                            transaction.setTransactionId(trade_no);
                            transaction.setUserId(orders.getUserId());
                            transaction.setFeeType("wyf");
                            transaction.setTotalMoney(new BigDecimal(total_amount_double));
                            transaction.setOutTradeNo(out_trade_no);
                            if(StrUtil.isNotEmpty(user.getNickName())){
                                transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                            }
                            transaction.setCreateTime(new Date());
                            transaction.setInOrOut(1);//动账  0 - 出账 1 - 进账
                            transaction.setRemark("物业费支付");
                            transaction.setPayPlatformId(orders.getPayPlatformId());
                            payTransactionService.save(transaction);
                        }

                        //发往后台 生成收据图片https://www.caihengyun.com/admin/common/download/settle/1265
                        //https://www.caihengyun.com/admin/common/download/settle
                        OkHttpClientUtil.getInstance().getData("https://www.caihengyun.com/admin/common/download/settle/" + orders.getId());

                        System.out.println("=====支付成功====");
                        logger.info("物业费订单号：" + out_trade_no + "支付成功");
                    }
                }
            }else{
                System.out.println("物业费订单号：" + out_trade_no + "不存在");
                logger.error("物业费订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(""+ex.getMessage());
        }
        return ret;
    }

    /**
     *  物业费 退款订单的 退款成功处理
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    private int refund_success_wyf(Map<String, String> params,int payType){
        String out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        if(payType == 2){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        }
        System.out.println("会员充值退款订单的订单号：" + out_trade_no + "，退款回调");
        int ret = 0;
        try{
            QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",out_trade_no).or().eq("order_no",out_trade_no);
            PropertyFeeOrder order = feeOrderService.getOne(qw);
            if(order != null){
                User user = userService.findById(order.getUserId());
                /**
                 * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 订单已完成 4 -  订单取消  5 - 已发起退款  6 - 同意退款  7 - 拒绝退款  8 - 退款完成
                 */
//                {msgType=wx.refund, payTime=2022-09-22 09:24:23, buyerCashPayAmt=10, connectSys=UNIONPAY,
//                        sign=5DA0C3672A9BCD5A16F9A04E6860D9F4D0FBEC981B4760FC00D087BE3D6B56ED, merName=跃豆智慧生活科技（10,
//                        settleDate=2022-09-22, billFunds=现金:10, buyerId=otdJ_uAqAjrCYNK0bhMQvJBNLbsI,
//                        mchntUuid=2d9081bd82f8c1a5018310959f25381a,
//                        tid=8699CXK6, sendBackAmount=10, instMid=MINIDEFAULT,
//                        refunAmount=0, attachedData=ELECTRIC_RECHARGE,
//                        cardAttr=BALANCE, closeTime=2022-09-22 09:25:04, targetOrderId=4200001538202209229323110439, signType=SHA256,
//                        billFundsDesc=现金支付0.10元。, YT=科技（山东）有限公司, seqId=29745038945N, merOrderId=32WT1663809856684,
//                        targetSys=WXPay, refundAmount=10, bankInfo=OTHERS, refundSettleDate=2022-09-22, refundOrderId=32WT1663809902685,
//                        tobuyerPayAmount=10, refundPayTime=2022-09-22 09:25:03,
//                        notifyId=6d5bcd4f-5501-46ab-89a0-1d3ac452cafe,
//                        subInst=100100, status=TRADE_REFUND}
                if(order.getState() == 6) {//发起退款 并同意申请 的才执行
                    String refund_fee = "";//  订单金额
                    String trade_no = "";//  订单号
                    double refund_fee_double = 0;

                    if (payType == 0) {//支付宝支付参数
                        refund_fee = params.get("refund_fee");
                        trade_no = params.get("transaction_id");//微信支付订单号
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                    } else if (payType == 1) {//微信支付参数
                        refund_fee = params.get("refund_fee");
                        trade_no = params.get("transaction_id");//微信支付订单号
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                    } else if (payType == 2) {// 农商行 支付参数
                        refund_fee = params.get("refundAmount");
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                        trade_no = params.get("targetOrderId");//微信支付订单号
                    }

                    /**
                     * 订单状态   0 - 交费申请 1 - 已生成交费清单    2 - 待支付  3- 支付中
                     *           4 - 已支付 5 - 订单取消   6 - 已发起退款  7 - 退款成功 8 - 退款失败
                     */
                    order.setState(7);
                    order.setRefundTransactionId(trade_no);
                    //0 未退款 1 申请中 2 已退款
                    order.setRefundStatus(2);
                    order.setRefundPrice(new BigDecimal(refund_fee_double));
                    order.setRefundTime(new Date());
                    boolean bl = feeOrderService.updateById(order);
                    if(bl){
                        //退款成功通知
//                        wxTemplateService.sendWxMsgVipOrderRefund(user,order,4);
                        ret = 1;
                    }

                    // 添加 微信支付的 动账记录
                    WxPayTransaction transaction = new WxPayTransaction();
                    transaction.setEstateId(order.getEstateId());
                    transaction.setEstateName(order.getEstateName());
                    transaction.setPayType(payType);// 0 -微信支付
                    transaction.setTransactionId(trade_no);
                    transaction.setUserId(user.getId());
                    transaction.setFeeType("wyf_refund");
                    transaction.setTotalMoney(new BigDecimal(refund_fee_double));
                    transaction.setOutTradeNo(out_trade_no);
                    if(StrUtil.isNotEmpty(user.getNickName())){
                        transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                    }
                    transaction.setCreateTime(new Date());
                    transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
                    transaction.setRemark("物业费退款");
                    transaction.setPayPlatformId(order.getPayPlatformId());
                    payTransactionService.save(transaction);

                    System.out.println("=====物业费退款成功====");
                    logger.info("物业费费用订单号：" + out_trade_no + "退款成功");
                }
            }else{
                System.out.println("物业费退款费用订单号：" + out_trade_no + "不存在");
                logger.error("物业费退款费用订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
        return ret;
    }

    /**
     * 商品订单的 退款成功处理
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    private int refund_success_product(Map<String, String> params,int payType){
        String out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        if(payType == 2){
            out_trade_no = params.get("merOrderId");// 本平台  商户订单号
        }
        System.out.println("商品退款订单的订单号：" + out_trade_no + "，退款回调");
        int ret = 0;
        try{
            QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",out_trade_no).or().eq("order_no",out_trade_no);
            ProductOrder order = productOrderService.getOne(qw);
            if(order != null){
                User user = userService.findById(order.getUserId());
                if(order.getStatus() == 7) {//发起退款 并同意申请 的才执行
                    String refund_fee = "";//  订单金额
                    String trade_no = "";//  订单号
                    double refund_fee_double = 0;

//                    refund_fee = params.get("refund_fee");
//                    trade_no = params.get("transaction_id");//微信支付订单号
//                    refund_fee_double = Double.valueOf(refund_fee) / 100;

                    if (payType == 0) {//支付宝支付参数
                        refund_fee = params.get("refund_fee");
                        trade_no = params.get("transaction_id");//微信支付订单号
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                    } else if (payType == 1) {//微信支付参数
                        refund_fee = params.get("refund_fee");
                        trade_no = params.get("transaction_id");//微信支付订单号
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                    } else if (payType == 2) {// 农商行 支付参数
                        refund_fee = params.get("refundAmount");
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                        trade_no = params.get("targetOrderId");//微信支付订单号
                    }


                    //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                    // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                    order.setStatus(8);
                    order.setTransactionId(trade_no);
                    order.setRefundPrice(new BigDecimal(refund_fee_double));
                    order.setRefundReasonTime(new Date());
                    ret = productOrderService.buyNormalUpdate(order,user);
                    if(ret > 0){
                        //退款成功通知
                        sendWxMsgRefund(user,order,4);
                    }

                    // 添加 微信支付的 动账记录
                    WxPayTransaction transaction = new WxPayTransaction();
                    transaction.setEstateId(order.getEstateId());
//                    transaction.setEstateName(order.getEstateName());
//                    transaction.setTransactionNo(order.getOutTradeNo());
                    transaction.setPayType(payType);// 0 -微信支付
                    transaction.setTransactionId(trade_no);
                    transaction.setUserId(user.getId());
                    transaction.setFeeType("product_refund");
                    transaction.setTotalMoney(new BigDecimal(refund_fee_double));
                    transaction.setOutTradeNo(order.getOutTradeNo());
                    if(StrUtil.isNotEmpty(user.getNickName())){
                        transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                    }
                    transaction.setCreateTime(new Date());
                    transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
                    transaction.setRemark("购买商品/服务的退款");
                    transaction.setPayPlatformId(order.getPayPlatformId());
                    payTransactionService.save(transaction);
                    System.out.println("=====退款成功====");
                    logger.info("普通商品订单号：" + out_trade_no + "退款成功");
                }
            }else{
                System.out.println("普通商品订单号：" + out_trade_no + "不存在");
                logger.error("普通商品订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
        return ret;
    }

    /**
     *  订单支付成功 公众号推送消息
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    public int sendWxMsg(User user, ProductOrder order, Integer template_type){
        try{
            List<UserMp> userMps = userMpService.selectUserMpList(order.getMerId());
            String access_token = wxTemplateService.getAccessToken(0);
            if(CollUtil.isNotEmpty(userMps)){
                for(UserMp userMp : userMps){
                    WxMsgTemplate template = null;
                    if(template_type == 7){//支付成功发送推送消息到 商家管理员微信上
                        template = getTemplateToMerManager(userMp,order,template_type);
                    }
                    String param = JSONUtil.parseObj(template).toString();
                    JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                    System.out.println("公众号推送消息 - 商家端响应信息:" + jsonObject.toString());
                }
            }
            WxMsgTemplate template = getTemplateToUser(user,order,3);
            String param = JSONUtil.parseObj(template).toString();
            JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
            System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());

        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    /**
     *  普通订单退款成功 公众号推送消息
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    public int sendWxMsgRefund(User user, ProductOrder order, Integer template_type){
        try{
            if(order != null){
//                String accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//                String access_token = redisTemplate.opsForValue().get("access_token_mp")!=null ? redisTemplate.opsForValue().get("access_token_mp").toString() : null;
//                if(StrUtil.isEmpty(access_token)){
//                    access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//                    redisTemplate.opsForValue().set("access_token_mp",access_token,3600L, TimeUnit.SECONDS);
//                }
                String access_token = wxTemplateService.getAccessToken(0);// WxMessage.getACCESSTOKEN(appidMp,secretMp);

                //给用户发送支付成功消息
                WxMsgTemplate template = getTemplateToUserByRefund(user,order,template_type);
                String param = JSONUtil.parseObj(template).toString();
                JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    /**
     *  发送推送消息到 商家管理员微信上
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateToUser(User user, ProductOrder order, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pages/order/productList/index?state=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();
            //您好，您的订单支付成功！
            //订单号：JPH81
            //支付金额：200元
            //支付时间：2016-04-01 12:32
            //感谢您的使用
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("尊敬的用户您好，您的订单支付成功！");
            m.put("first",first);

            //订单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(order.getOrderNo());
            m.put("keyword1",keyword1);

            //支付金额
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(MathUtil.getDoubleUp(order.getPayPrice().doubleValue()) + "元");
            m.put("keyword2",keyword2);

            //支付时间
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(DateUtil.getTime(order.getPayTime()));
            m.put("keyword3",keyword3);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("感谢您的使用");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /**
     *  发送推送消息到 商家管理员微信上
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateToUserByRefund(User user, ProductOrder order, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pages/order/productList/index?index=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();
//            {{first.DATA}}
//            订单号：{{keyword1.DATA}}
//            商品：{{keyword2.DATA}}
//            退款金额：{{keyword3.DATA}}
//            客户名称：{{keyword4.DATA}}
//            退款原因：{{keyword5.DATA}}
//            {{remark.DATA}}
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            if(order.getOrderType() == 4){
                first.setValue("尊敬的用户您好，您的拼团未成团，订单已退款！");
            }else{
                first.setValue("尊敬的用户您好，您的订单已退款完成！");
            }
            m.put("first",first);

            //订单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(order.getOrderNo());
            m.put("keyword1",keyword1);

            //商品
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            Product product = productService.getProductByOrderId(order.getId());
            if(product!=null){
                keyword2.setValue(product.getStoreName());
            }else{
                keyword2.setValue("");
            }
            m.put("keyword2",keyword2);

            //客户名称
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(EmojiParser.parseToUnicode(user.getNickName()));
            m.put("keyword3",keyword3);

            //退款金额
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(MathUtil.getDoubleUp(order.getRefundPrice().doubleValue())+"");
            m.put("keyword4",keyword4);

            //备注信息
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("感谢您的使用,退款金额以到账为准");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /**
     *  发送推送消息到 商家管理员微信上
     * @param userMp
     * @param order
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateToMerManager(UserMp userMp, ProductOrder order, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pagesMer/pages/orderList/index?state=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();
//            有客户要看房啦，请及时处理
//            提交时间：2018-07-09
//            订单类型：看房
//            客户信息：张丽 电话：1111111111111
//            房屋信息：杭州市西湖区湖墅南路111号
//            感谢您的使用。
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("尊敬的商家用户您好，您有新客户订单");
            m.put("first",first);

            //提交时间
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(DateUtil.getSdfTimesCN());
            m.put("keyword1",keyword1);

            //订单类型
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue("商家服务");
            m.put("keyword2",keyword2);

            //客户信息
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(order.getRealName() + "(" + order.getUserPhone()+")");
            m.put("keyword3",keyword3);

            //房屋信息
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(order.getUserAddress());
            m.put("keyword4",keyword4);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("客户已下单，请及时跟进处理");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }
}
